package com.neuedu.his.config;

import com.neuedu.his.mapper.RegisterMapper;
import com.neuedu.his.po.Register;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class DoctorPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private RegisterMapper registerMapper;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取当前登录医生ID
        String doctorIdStr = request.getHeader("doctorId");
        if (doctorIdStr == null || doctorIdStr.isEmpty()) {
            sendErrorResponse(response, HttpStatus.UNAUTHORIZED, "医生身份验证失败");
            return false;
        }

        Integer doctorId;
        try {
            doctorId = Integer.valueOf(doctorIdStr);
        } catch (NumberFormatException e) {
            sendErrorResponse(response, HttpStatus.BAD_REQUEST, "医生ID格式错误");
            return false;
        }

        // 检查挂号ID权限
        String registIdStr = getRegistIdFromRequest(request);
        if (registIdStr != null && !registIdStr.isEmpty()) {
            try {
                Integer registId = Integer.valueOf(registIdStr);
                Register register = registerMapper.selectById(registId);

                if (register == null || !Objects.equals(register.getUserid(), doctorId)) {
                    sendErrorResponse(response, HttpStatus.FORBIDDEN, "无权限访问该患者信息");
                    return false;
                }

                // 检查挂号状态是否为待就诊(1)或就诊中(2)
                if (register.getVisitstate() != 1 && register.getVisitstate() != 2) {
                    sendErrorResponse(response, HttpStatus.FORBIDDEN, "患者不在可操作状态");
                    return false;
                }
            } catch (NumberFormatException e) {
                sendErrorResponse(response, HttpStatus.BAD_REQUEST, "挂号ID格式错误");
                return false;
            }
        }

        return true;
    }

    private String getRegistIdFromRequest(HttpServletRequest request) {
        // 从参数获取
        String registIdStr = request.getParameter("registId");
        if (registIdStr != null) {
            return registIdStr;
        }

        // 从路径变量中获取
        String path = request.getRequestURI();
        String[] pathParts = path.split("/");
        for (int i = 0; i < pathParts.length - 1; i++) {
            if ("register".equals(pathParts[i]) && i + 1 < pathParts.length) {
                return pathParts[i + 1];
            }
            if ("medical-record".equals(pathParts[i]) && i + 1 < pathParts.length) {
                return pathParts[i + 1];
            }
        }
        return null;
    }

    private void sendErrorResponse(HttpServletResponse response, HttpStatus status, String message) throws Exception {
        response.setStatus(status.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(String.format("{\"message\":\"%s\",\"success\":false}", message));
    }
}